import React from 'react';
import './index.css';

/*
  学习目标：组件通信-子传父-还原删除功能

*/
export default class App extends React.Component {
  state = {
    username: '',
    content: '',
    list: [
      {
        id: 1,
        username: '思聪',
        content: '想你的夜',
      },
      {
        id: 2,
        username: '马芸',
        content: '我对钱不感兴趣',
      },
      {
        id: 3,
        username: '王简林',
        content: '实现一个小目标',
      },
    ],
  };

  handleChange = (e) => {
    const { name, value } = e.target;
    this.setState({ [name]: value.trim() });
  };
  handleSubmit = (e) => {
    e.preventDefault();
    const { username, content, list } = this.state;
    if (!username.trim() || !content.trim()) {
      return;
    }

    const newList = {
      id: Date.now(),
      username,
      content,
    };
    this.setState({ list: [newList, ...list], username: '', content: '' });
  };

  handleDelById = (id) => {
    const list = this.state.list.filter((item) => item.id !== id);
    this.setState({ list });
  };

  handleClear = () => {
    this.setState({ list: [] });
  };

  render() {
    const { list, username, content } = this.state;
    return (
      <div className="app">
        <Header
          username={username}
          content={content}
          handleSubmit={this.handleSubmit}
          handleChange={this.handleChange}
          handleClear={this.handleClear}
        ></Header>
        {/* 1. 传一个回调函数过来 */}
        <CommentList list={list} handleDelById={this.handleDelById}></CommentList>
      </div>
    );
  }
}

function CommentList({ list, handleDelById }) {
  // 2. 子组件调用
  return list.length ? (
    <ul>
      {list.map((item) => (
        <li key={item.id}>
          <h3>评论人: {item.username}</h3>
          <p>评论内容：{item.content}</p>
          <button onClick={() => handleDelById(item.id)}>删除</button>
        </li>
      ))}
    </ul>
  ) : (
    <div>暂无数据</div>
  );
}
function Header({ username, content, handleChange, handleSubmit, handleClear }) {
  return (
    <form>
      <input
        onChange={handleChange}
        value={username}
        name="username"
        className="user"
        type="text"
        placeholder="请输入评论人"
      />
      <br />
      <textarea
        onChange={handleChange}
        value={content}
        name="content"
        className="content"
        cols="30"
        rows="10"
        placeholder="请输入评论内容"
      />
      <br />
      <button onClick={handleSubmit}>发表评论</button>

      <button type="button" onClick={handleClear}>
        清空评论
      </button>
    </form>
  );
}
